<template>
  <div class="flx-s">
    <div class="flx-s">
      <div
        class="pos-rlt mr10"
        v-for="(img,i) in list"
        :key="`img${i}`">
        <ZgImgHolder
          :src="img"
          :width="100"
          :height="100"
        />
        <i @click="remove(i)" class="fa fa-times pos-abs cpt" style="top:0;right:0"/>
      </div>
    </div>
    <a-upload
      name="file"
      :accept="accept"
      :multiple="false"
      :data="param"
      :action="API_URL + '/zg-system/file/upload'"
      @change="handleChange"
      :headers="headers"
      :showUploadList="false"
      :beforeUpload="handleBeforeUpload"
    >
      <div class="holder" :style="{width:`100px`,height:`${100}px`}">
        <a-icon :type="loading ? 'loading' : 'plus'" />
      </div>
    </a-upload>
    <div
      class="w200 ml10 fs12"
      style="color:#999;word-wrap: break-word;"
      v-if="note&&note.length>0">
      {{ note }}
    </div>
  </div>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  model: {
    prop: 'modelVal', // 指向props的参数名
    event: 'change'// 事件名称
  },
  props: {
    modelVal: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '.png,.jpg,.jpeg,.gif'
    },
    size: {
      type: Number,
      default: 10
    },
    note: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      loading: false,
      list: this.modelVal.split(',').filter(t => {
        return t.length > 0
      }),
      headers: {},
      param: {
        module: 'default'
      }
    }
  },
  mounted () {
    this.headers[ACCESS_TOKEN] = storage.get(ACCESS_TOKEN)
  },
  watch: {
    modelVal (newVal) {
      this.list = newVal.split(',').filter(t => {
        return t.length > 0
      })
    },
    list (newVal) {
      this.$emit('change', newVal.join(','))
    }
  },
  methods: {
    remove (i) {
      this.list.splice(i, 1)
    },
    handleBeforeUpload (file) {
      return file.size / 1024 / 1024 < this.size
    },
    handleChange (info) {
      const status = info.file.status
      if (status === 'uploading') {
        this.loading = true
      } else if (status === 'done') {
        this.loading = false
        const res = info.file.response
        if (res.code !== 1) {
          this.$message.error(res.message)
        } else {
          const json = res.data
          const f = {
            id: json.id,
            name: json.name,
            size: json.size,
            path: json.path
          }
          this.$emit('upload', f)
          this.list.push(json.path)
        }
      } else if (status === 'error') {
        this.loading = false
        this.$message.error(`${info.file.name} 文件上传失败.`)
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
